import { nailerService } from "./../../providers/nailerService";
import { StorageService } from "./../../providers/StorageService";
import { BasePage } from "./../basePage";
import { Component, Injector } from "@angular/core";
import { IonicPage, ActionSheetController } from "ionic-angular";
import { File } from "@ionic-native/file";
import { Camera } from "@ionic-native/camera";
import { FilePath } from "@ionic-native/file-path";
declare var cordova: any;
/**
 * Generated class for the CommentPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
  selector: "page-comment",
  templateUrl: "comment.html"
})
export class CommentPage extends BasePage {
  oboaut = true;
  oboaut1 = false;
  oboaut2 = false;
  /**专业技能 */
  imgBox = 0;
  score: any = {
    star: 1,
    starMap: ["一般", "一般", "好", "好", "非常好"]
  };

  /**服务态度 */
  score1: any = {
    star: 1,
    starMap: ["一般", "一般", "好", "好", "非常好"]
  };
  lastImage: string = null;
  /**店铺环境 */
  score2: any = {
    star: 1,
    starMap: ["一般", "一般", "好", "好", "非常好"]
  };

  goods = {
    user_id: 0,
    order_sn: "",
    remark_level: 1,
    remark_content: "",
    shop_level: 1,
    skill_level: 1,
    service_level: 1,
    remark_img_first: "",
    remark_img_second: "",
    remark_img_third: ""
  };
  imgUrl = ["assets/img/Comment/shangchuan@2x.png"];
  lg = "assets/img/Comment/shangchuan@2x.png";
  fileObjList = [];
  userinfo = {};
  constructor(
    injector: Injector,
    public actionSheetCtrl: ActionSheetController,
    public nailerservice: nailerService,
    public stc: StorageService,
    public camera: Camera,
    public file: File,
    public filePath: FilePath
  ) {
    super(injector);
    this.userinfo = this.stc.read("userinfo");
  }

  ionViewDidLoad() {
    /**检测是否有商品，没有的话就返回 */
    this.checkgoodid();
  }
  ionViewDidEnter() {
    console.log("3.0 ionViewDidEnter 当进入页面时触发");
    console.log("1111");

  }
  /**检测是否有商品，没有的话就返回 */
  checkgoodid() {
    console.log(this.navParams.get("item"));
    let item=this.navParams.get("item");
    this.goods. user_id=this.userinfo['user_id'];
    this.goods.order_sn= item['order_sn'];
    //this.goods.order_sn = this.navParams.get("order_sn");
    if (!this.goods.order_sn) {
      let toast = this.toastCtrl.create({
        message: "没有查询到订单，系统出错",
        duration: 2000,
        position: "bottom"
      });
      toast.present();
      this.navCtrl.pop();
    }
  }

  /**返回上一个页面 */
  dismissCLI(i) {
    this.stc.write("back",this.navParams.get("par"));
    console.log(this.goods);
    if(i){
      this.viewCtrl.dismiss(i)
    }else{
      this.viewCtrl.dismiss()
    } 
  }

  /** 发布 */
  issue() {
    this.goods.user_id = this.userinfo["user_id"];
    console.log();
    console.log(this.goods);
    console.log(111);
    // this.commentOrderAPI();
  }

  /**专业技能 */
  chooseStar(e) {
    let star = parseInt(e.target.dataset.index);
    this.score.star = star;
    this.goods.skill_level = star;
  }

  /**服务态度*/
  chooseStar1(e1) {
    let star1 = parseInt(e1.target.dataset.index);
    this.score1.star = star1;
    this.goods.service_level = star1;
  }

  /** 店铺环境 */
  chooseStar2(e2) {
    let star2 = parseInt(e2.target.dataset.index);
    this.score2.star = star2;
    this.goods.shop_level = star2;
  }
  /** 点赞 */
  obout(stu, i) {
    if (i == 1) {
      this.oboaut = stu;
      this.oboaut1 = false;
      this.oboaut2 = false;
    }
    if (i == 2) {
      this.oboaut = false;
      this.oboaut1 = stu;
      this.oboaut2 = false;
    }
    if (i == 3) {
      this.oboaut = false;
      this.oboaut1 = false;
      this.oboaut2 = stu;
    }
    this.goods.remark_level = i;
  }
  /** 相册 */

  Remimg(i) {   
    if(this.imgUrl.length<=3){
      this.imgUrl.splice(i,1);
      if(this.imgUrl[this.imgUrl.length-1]!='assets/img/Comment/shangchuan@2x.png'){
        this.imgUrl.push('assets/img/Comment/shangchuan@2x.png')
      }
    }
    

  }
  presentActionSheetCamr(i) {
    this.imgBox = i;
   

    let actionSheet = this.actionSheetCtrl.create({
      title: "选择",
      buttons: [
        {
          text: "拍照上传",
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.CAMERA);
          }
        },
        {
          text: "从相册上传",
          handler: () => {
            this.takePicture(this.camera.PictureSourceType.PHOTOLIBRARY);
          }
        },

        {
          text: "取消",
          role: "cancel",
          handler: () => {
            console.log("Cancel clicked");
          }
        }
      ]
    });
    actionSheet.present();
  }

  copyFileToLocalDir(namePath, currentName, newFileName) {
    this.file
      .copyFile(namePath, currentName, cordova.file.dataDirectory, newFileName)
      .then(
        success => {
          this.lastImage = newFileName;
        },
        error => {
          // super.showToast(this.toastCtrl, "存储图片到本地图库出现错误。");
        }
      );
  }
  createFileName() {
    var d = new Date(),
      n = d.getTime(),
      newFileName = n + ".jpg"; //拼接文件名
    return newFileName;
  }
  takePicture(sourceType) {
    //定义相机的一些参数
    var options = {
      quality: 100, //图片的质量
      sourceType: sourceType,
      saveToPhotoAlbum: false, //是否保存拍摄的照片到相册中去
      correctOrientation: true //是否纠正拍摄的照片的方向
    };

    //获取图片的方法
    this.camera.getPicture(options).then(
      imagePath => {
        //特别处理 android 平台的文件路径问题
        if (
          this.platform.is("android") &&
          sourceType === this.camera.PictureSourceType.PHOTOLIBRARY
        ) {
          this.filePath
            .resolveNativePath(imagePath) //获取 android 平台下的真实路径
            .then(filePath => {
              //获取正确的路径
              let correctPath = filePath.substr(
                0,
                filePath.lastIndexOf("/") + 1
              );
              //获取正确的文件名
              let currentName = imagePath.substring(
                imagePath.lastIndexOf("/") + 1,
                imagePath.lastIndexOf("?")
              );
              this.copyFileToLocalDir(
                correctPath,
                currentName,
                this.createFileName()
              );
              this.imgUrl[this.imgBox] = imagePath;
            if(this.imgUrl.length<3){
              this.imgUrl.push(this.lg)
            }
            });
          /**
           *
           */
          this.toastCtrl.create({
              // message: '安卓平台' + correctPath + '+ && +' + currentName,
              message: this.imgBox + "图片地址" + this.imgUrl[0],
              duration: 3000,
              position: "top"
            })
            .present();
        } else {
          //获取正确的路径
          var correctPath = imagePath.substr(0, imagePath.lastIndexOf("/") + 1);
          //获取正确的文件名
          var currentName = imagePath.substr(imagePath.lastIndexOf("/") + 1);
          this.copyFileToLocalDir(
            correctPath,
            currentName,
            this.createFileName()
          );

          this.imgUrl[this.imgBox] = imagePath;
          if(this.imgUrl.length<3){
            this.imgUrl.push(this.lg)
          }
      
          /**
           *
           */
          this.toastCtrl.create({
              // message: 'IOS平台' + correctPath + '+ && +' + currentName,
              message: "图片地址" + this.imgUrl[0],
              duration: 3000,
              position: "top"
            })
            .present();
        }
      },
      err => {
        // super.showToast(this.toastCtrl, "选择图片出现错误，请在 App 中操作或检查相关权限。");
        /**
         *
         */
        this.toastCtrl
          .create({
            message: err,
            duration: 3000,
            position: "middle"
          })
          .present();
      }
    );
  }

  /**发布评论 */
  async commentOrderAPI() {
    this.goods.remark_img_first=this.imgUrl[0];
    this.goods.remark_img_second=this.imgUrl[1];
    this.goods.remark_img_third=this.imgUrl[2];
    if (this.goods.remark_img_first == "assets/img/Comment/shangchuan@2x.png") {
      this.goods.remark_img_first = "";
    }
    console.log(this.goods)
    let res = await this.nailerservice.commentOrderAPI(this.goods);
    console.log(res);
    if (res.code == 1) {
      let toast = this.toastCtrl.create({
        message: res.msg,
        duration: 2000,
        position: "bottom"
      });
      toast.present();
      setTimeout(()=>{
        this.dismissCLI("ok");
      },1000)
    } else {
      let toast = this.toastCtrl.create({
        message: res.msg,
        duration: 2000,
        position: "bottom"
      });
      toast.present();
    }
  }
}
